package top.datacluster.basic.algorithm.leetcode;

/**
 * Write a function to find the longest common prefix string amongst an array of strings.
 *
 * If there is no common prefix, return an empty string "".
 *
 * Example 1:
 *
 * Input: ["flower","flow","flight"]
 * Output: "fl"
 * Example 2:
 *
 * Input: ["dog","racecar","car"]
 * Output: ""
 * Explanation: There is no common prefix among the input strings.
 * Note:
 *
 * All given inputs are in lowercase letters a-z.
 */
public class CommonPrefixLeetcode14 {

    public static String longestCommonPrefix(String[] strs) {
        int j = 0;
        char c;
        int f;
        StringBuffer sb = new StringBuffer();
        if (strs.length == 0){
            return "";
        }
        while (true){
            if (j < strs[0].length()){
                f = strs[0].charAt(j);
            }else{
                break;
            }
            for (int i = 1; i < strs.length;i++){
                if (j < strs[i].length()){
                    c = strs[i].charAt(j);
                    if (c != f){
                        return sb.toString();
                    }
                }else{
                    return sb.toString();
                }

            }
            j++;
            sb.append((char)f);
        }
        return sb.toString();

    }

    public static void main(String[] args) {
        String[] str = new String[]{"flower","flow","flight"};
        System.out.println(longestCommonPrefix(str));
    }
}
